package com.Downloaders;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.Managers.DirManagerClass;
import com.Managers.LogManagerClass;
import com.Managers.PictureManagerClass;
import com.shareup.R;


public class ThumbDownloader extends AsyncTask<String, String, Bitmap> {

    private ThumbnailCompleted completeBitmap;

    private ThumbnailPathCompleted completePath;

    private final Context context;

    private String downloadedFileName;

    private boolean isCover;

    private final String mensaje;

    private final ProgressDialog progress;

    private final String Url;

    public interface ThumbnailCompleted {

        void Completed(Bitmap thumb);

    }

    public abstract interface ThumbnailPathCompleted {

        void Completed(String path);
    }

    public ThumbDownloader(Context context, String url) {

        super();

        Url = url;
        this.context = context;
        this.progress = new ProgressDialog(context);
        this.mensaje = context.getResources().getString(R.string.dialog_loading_header);
    }

    public void setCompleteBitmap(ThumbnailCompleted complete) {

        this.completeBitmap = complete;
    }

    public void setCompletePath(ThumbnailPathCompleted completePath) {

        this.completePath = completePath;
    }

    public void setCover(boolean isCover) {

        this.isCover = isCover;
    }

    private Bitmap downloadImage(String URL, String SDPATH) {

        InputStream input = null;
        OutputStream output = null;
        //
        try {
            //
            URL url = new URL(URL);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            conexion.getContentLength();
            //
            input = url.openStream();
            //
            output = new FileOutputStream(new File(SDPATH));
            //
            //
            //
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            //
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                //
                output.write(buffer, 0, bytesRead);
                //
            }

            return PictureManagerClass.ImageResize(Uri.fromFile(new File(SDPATH)), context);

        }
        catch (Exception x) {
            Log.e("ThumbDownloader", x.getMessage());
            LogManagerClass.writeLog("ThumbDownloader:"
                        + x.getMessage());
            return null;
        }
        finally {
            try {
                output.close();
            }
            catch (Exception x) {
                Log.e("ThumbDownloader", x.getMessage());
                LogManagerClass.writeLog("ThumbDownloader:"
                            + x.getMessage());
                downloadImage(URL, SDPATH);
            }
        }
    }

    private String makePath(String iTag) {

        String fullSdPath = "";
        String withOutExt = "";
        //
        String[] sp = iTag.split("/");
        withOutExt = sp[sp.length - 1];

        if (isCover)
            fullSdPath = DirManagerClass.MainPath
                        + DirManagerClass.MapThumbsPath + withOutExt;
        else
            fullSdPath = DirManagerClass.MainPath
                        + DirManagerClass.MapThumbsPath + "thumb_"
                        + withOutExt;

        return fullSdPath;
    }

    private Bitmap verifyForFile(String url, String path) {

        File mbmp = new File(path);

        if (!mbmp.exists()) {

            return downloadImage(url, path);
        }
        else {

            return PictureManagerClass.ImageResize(Uri.fromFile(mbmp), context);
        }

    }

    @Override
    protected Bitmap doInBackground(String... arg0) {

        downloadedFileName = makePath(Url);
        return verifyForFile(Url, downloadedFileName);
    }

    @Override
    protected void onPostExecute(Bitmap result) {

        if (completePath != null)
            completePath.Completed(downloadedFileName);
        else {
            completeBitmap.Completed(result);
            progress.dismiss();

        }

    }

    @Override
    protected void onPreExecute() {

        if (completeBitmap != null) {
            progress.setMessage(mensaje);
            progress.setCancelable(false);
            progress.setIndeterminate(true);
            progress.show();
        }

    }

}
